// Enable the visual refresh
google.maps.visualRefresh = true;

//executes on page load.
function initialize() {

    // map options for a scalable hybrid map scentered on Bulgaria
    var mapOptions = {
        center: new google.maps.LatLng(42.5, 25.5),
        zoom: 7,
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    //create the map from the options.
    var map = new google.maps.Map(document.getElementById("map-canvas"),
                                  mapOptions);

    // if the places library is included enable autocomplete using google
    // places.
    if (google.maps.places) {

        //get the search input from the page.
        var input = (document.getElementsByName('search')[0]);

        // create an autocomplete object using that search input.
        var autocomplete = new google.maps.places.Autocomplete(input);

        autocomplete.bindTo('bounds', map);

        // infoWindow and marker for the place found.
        var infowindow = new google.maps.InfoWindow();
        var marker = new google.maps.Marker({
            map: map
        });

        // define behaviour of the autocomplete.
        google.maps.event.addListener(autocomplete,'place_changed',function(){
            //remove the old stuff
            infowindow.close();
            marker.setVisible(false);
            input.className = '';
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                // Inform the user that the place was not found and return.
                input.className = 'notfound';
                return;
            }

            // If the place has a geometry, then present it on a map.
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);  // Why 17? Because it looks good.
            }
            marker.setIcon(/** @type {google.maps.Icon} */({
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(35, 35)
            }));
            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            var address = '';
            if (place.address_components) {
                address = [
                    (place.address_components[0]
                     && place.address_components[0].short_name || ''),
                    (place.address_components[1]
                     && place.address_components[1].short_name || ''),
                    (place.address_components[2]
                     && place.address_components[2].short_name || '')
                ].join(' ');
            }

            infowindow.setContent('<div><strong>' + place.name
                                  + '</strong><br>' + address);
            infowindow.open(map, marker);
        });
    }

    // if the drawing library is included.
    if (google.maps.drawing) {

        // make a new drawingmanager, that can do markers, circles,
        // and rectangles.
        var drawingManager = new google.maps.drawing.DrawingManager({
            drawingMode: google.maps.drawing.OverlayType.MARKER,
            drawingControl: true,
            drawingControlOptions: {
                position: google.maps.ControlPosition.TOP_CENTER,
                drawingModes: [
                    google.maps.drawing.OverlayType.MARKER,
                    google.maps.drawing.OverlayType.CIRCLE,
                    google.maps.drawing.OverlayType.RECTANGLE
                ]
            },
            circleOptions: {
                fillColor: '#ffff00',
                fillOpacity: 0.3,
                strokeWeight: 5,
                clickable: false,
                zIndex: 1,
                editable: true
            },
            rectangleOptions: {
                fillColor: '#ffff00',
                fillOpacity: 0.3,
                strokeWeight: 5,
                clickable: false,
                zIndex: 1,
                editable: true
            }

        });
        //bind it to the map
        drawingManager.setMap(map);

// add.php page

        // the drawn overlay
        var overlay;
        
        // define behaviour for the manager when something is drawn.
        google.maps.event.addListener(drawingManager, 'overlaycomplete',
                                      function(event) {
            // get rid of the old stuff.
            if (overlay) {
                overlay.setMap(null);
            }
            // and get the new.
            overlay = event.overlay;
            var coords; //coordinates of the center
            var radius; // radius if circle, 0 otherwise
            var bounds; // coords of the bounds of a rectagle, 4x0 otherwise
            var submit; // coords, radius, bounds
            // if a marker is drawn just place it.
            if (event.type == google.maps.drawing.OverlayType.MARKER) {
                coords = overlay.getPosition().toString();
                coords = preparecoords(coords);
                bounds = radius = 0;
                submit = coords + ",0,0,0,0,0";
            }
            // if a circle is drawn place it and subscribe for events.
            if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
                coords = overlay.getCenter().toString();
                coords = preparecoords(coords);
                radius = overlay.getRadius() + "";
                bounds = 0;
                submit = coords + "," + radius + ",0,0,0,0";
                // when the center is changed modify data on page.
                google.maps.event.addListener(overlay, 'center_changed',
                                              function() {
                    coords = overlay.getCenter().toString();
                    coords = preparecoords(coords);
                    radius = overlay.getRadius() + "";
                    submit = coords + "," + radius + ",0,0,0,0";
                    document.getElementsByName("coords")[0].setAttribute(
                                                              "value", coords);
                    document.getElementsByName("submit")[0].setAttribute(
                                                              "value", submit);
                });
                // when the radius is changed modify data on page.
                google.maps.event.addListener(overlay, 'radius_changed',
                                              function() {
                    coords = overlay.getCenter().toString();
                    coords = preparecoords(coords);
                    radius = overlay.getRadius() + "";
                    submit = coords + "," + radius + ",0,0,0,0";
                    document.getElementsByName("submit")[0].setAttribute(
                                                              "value", submit);
                });
            }
            // if a rectangle is drawn place it and subscribe for events.
            if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
                bounds = overlay.getBounds();
                coords = bounds.getCenter().toString();
                radius = "0";
                coords = preparecoords(coords);
                bounds = preparebounds(bounds.toString());
                submit = coords + "," + radius + "," + bounds;
                // when the bounds are changed modify data on page.
                google.maps.event.addListener(overlay, 'bounds_changed',
                                              function() {
                    bounds = overlay.getBounds();
                    coords = bounds.getCenter().toString();
                    radius = "0";
                    coords = preparecoords(coords);
                    bounds = preparebounds(bounds.toString());
                    submit = coords + "," + radius + "," + bounds;
                    document.getElementsByName("coords")[0].setAttribute(
                                                              "value", coords);
                    document.getElementsByName("submit")[0].setAttribute(
                                                              "value", submit);
                });
            }
            // modifying data on page on first draw of an overlay.
            document.getElementsByName("coords")[0].setAttribute(
                                                              "value", coords);
            document.getElementsByName("submit")[0].setAttribute(
                                                              "value", submit);
        });

        // gets the string of coords, removes parenths and spaces.
        function preparecoords(coords) {
            coords = coords.slice(1, coords.length-1).split(",");
            for (i = 0; i < coords.length; ++i) {
                coords[i] = coords[i].trim();
            }
            return coords.join();
        }

        // gets the string of bounds, removes parenths and spaces.
        function preparebounds(bounds) {
            bounds = bounds.split(",");
            for (i = 0; i < bounds.length; ++i) {
                if (i%2 == 0) {
                    bounds[i] = bounds[i].slice(2, bounds[i].length);
                } else {
                    bounds[i] = bounds[i].slice(1, bounds[i].length-2);
                }
            }
            return bounds.join();
        }

// for selected.php and edit.php

        //get the data from html, which comes from php.
        var obname = document.getElementById("hname").value;
        var obcoords = document.getElementById("hcoords").value;
        var obdescr = document.getElementById("hdescr").value;
        //select page?
        var select = document.getElementById("hhidedraw");

        //if we actually got something => we're in selected or edit pages.
        if (obname !== null && obcoords !== null && obdescr !== null) {

            //don't want to be able to draw or see the control.
            drawingManager.setOptions({
                drawingMode: null,
                drawingControl: false
            });

            obcoords = obcoords.split(",");
            var obj;
            var incoords;
            if (Number(obcoords[obcoords.length-1])) { // bounds = >rectangle
                //if coordinates are for rectangle - draw it.
                cntr = new google.maps.LatLng(obcoords[0], obcoords[1]);
                r = obcoords[2];
                sw = new google.maps.LatLng(obcoords[3], obcoords[4]);
                ne = new google.maps.LatLng(obcoords[5], obcoords[6]);
                bnds = new google.maps.LatLngBounds(sw, ne);
                var rectOptions = {
                    fillColor: '#ffff00',
                    fillOpacity: 0.3,
                    strokeWeight: 5,
                    clickable: false,
                    zIndex: 1,
                    editable: false,
                    map: map,
                    bounds: bnds
                };
                obj = new google.maps.Rectangle(rectOptions);
                //if page is edit, show data. Showing for selected is more
                // precise that's why it's done by php in the actual page.
                if (select === null) {
                    document.getElementsByName("name")[0].value = obname;
                    document.getElementsByName("coords")[0].value = obcoords[0] + "," + obcoords[1];
                    document.getElementsByName("descr")[0].value = obdescr;
                    document.getElementsByName("submit")[0].value = obcoords;
                    //make rectangle editable
                    obj.setEditable(true);
                    //update data upon edit.
                    google.maps.event.addListener(obj, "bounds_changed", function () {
                        newbounds = preparebounds(obj.getBounds().toString());
                        newcoords = preparecoords(obj.getBounds().getCenter().toString());
                        document.getElementsByName("coords")[0].value = newcoords;
                        document.getElementsByName("submit")[0].value = newcoords + ",0," + newbounds;
                    });
                }
                map.setCenter(cntr);
            } else if (Number(obcoords[2])) { //radius => circle
                //if coordinates are for circle - draw it.
                cntr = new google.maps.LatLng(obcoords[0], obcoords[1]);
                r = Number(obcoords[2]);
                var circOptions = {
                    fillColor: '#ffff00',
                    fillOpacity: 0.3,
                    strokeWeight: 5,
                    clickable: false,
                    zIndex: 1,
                    editable: false,
                    map: map,
                    center: cntr,
                    radius: r
                };
                obj = new google.maps.Circle(circOptions);
                //if page is edit, show data. Showing for selected is more
                // precise that's why it's done by php in the actual page.
                if (select === null) {
                    document.getElementsByName("name")[0].value = obname;
                    document.getElementsByName("coords")[0].value = obcoords[0] + "," + obcoords[1];
                    document.getElementsByName("descr")[0].value = obdescr;
                    document.getElementsByName("submit")[0].value = obcoords;
                    //make circle editable
                    obj.setEditable(true);
                    //update data upon edit.
                    google.maps.event.addListener(obj, "center_changed", function () {
                        newcoords = preparecoords(obj.getCenter().toString());
                        document.getElementsByName("coords")[0].value = newcoords;
                        obcoords[0] = newcoords.split(",")[0];
                        obcoords[1] = newcoords.split(",")[1];
                        document.getElementsByName("submit")[0].value = obcoords;
                    });
                    google.maps.event.addListener(obj, "radius_changed", function () {
                        obcoords[2] = obj.getRadius().toString();
                        document.getElementsByName("submit")[0].value = obcoords;
                    });
                }
                map.setCenter(cntr);
            } else { //marker
                //if coordinates are for marker - draw it.
                cntr = new google.maps.LatLng(obcoords[0], obcoords[1]);
                var markOptions = {
                    clickable: false,
                    zIndex: 1,
                    map: map,
                    position: cntr,
                };
                obj = new google.maps.Marker(markOptions);
                //if page is edit, show data. Showing for selected is more
                // precise that's why it's done by php in the actual page.
                if (select === null) {
                    document.getElementsByName("name")[0].value = obname;
                    document.getElementsByName("coords")[0].value = obcoords[0] + "," + obcoords[1];
                    document.getElementsByName("descr")[0].value = obdescr;
                    document.getElementsByName("submit")[0].value = obcoords;
                    obj.setDraggable(true);
                    //update data upon drag.
                    google.maps.event.addListener(obj, "drag", function (me) {
                        newcoords = preparecoords(me.latLng.toString());
                        document.getElementsByName("coords")[0].value = newcoords;
                        obcoords[0] = newcoords.split(",")[0];
                        obcoords[1] = newcoords.split(",")[1];
                        document.getElementsByName("submit")[0].value = obcoords;
                    });
                }
                map.setCenter(cntr);
            }

        }
 
    }
}

//make the initialization run upon page load.
google.maps.event.addDomListener(window, 'load', initialize);

//for login - open a new window.
function loginPrompt() {
    loginWin = window.open("./login.php", "", "height=120, width=300, " +
                           "resizable='no', left=500p, top=200p, scrollbars='no'", "False");
}

//reload upon pressing reset button
function resetform() {
    document.location.reload();
}

//when cancel is hit load index.php
function cancelform() {
    window.open("./index.php", "_parent");
}